package com.jit.monitor.presenter.user;

import android.annotation.SuppressLint;

import com.jit.baselib.ui.base.BaseActivity;
import com.jit.baselib.ui.base.BasePresenter;
import com.jit.baselib.util.ui.ResHelper;
import com.jit.monitor.R;
import com.jit.monitor.base.ApiNormalRetrofit;
import com.jit.monitor.commom.AppConstant;
import com.jit.monitor.model.cache.UserCache;
import com.jit.monitor.util.JPushHelper;
import com.jit.monitor.view.LoginAtView;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @author crazyZhangxl on 2018/11/21.
 * Describe:
 */
public class LoginAtPresenter  extends BasePresenter<LoginAtView> {
    public LoginAtPresenter(BaseActivity context) {
        super(context);
    }

    @SuppressLint("CheckResult")
    public void  doLogin(String userName, String pwd){
        getView().showLoadingDialog();
        ApiNormalRetrofit.getInstance().requestLogin(userName,pwd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(loginResponseBaseResponse -> {
                    getView().hideLoadingDialog();
                    if (loginResponseBaseResponse.getCode() == AppConstant.REQUEST_SUCCESS){
                        UserCache.setUserToken(ResHelper.getString(R.string.token_plus,
                                loginResponseBaseResponse.getData().getTokenInfo().getToken_type(),
                                loginResponseBaseResponse.getData().getTokenInfo().getAccess_token()));
                        UserCache.setUserName(userName);
                        UserCache.setUserPwd(pwd);
                        // 缓存用户ID
                        UserCache.setUserID(loginResponseBaseResponse.getData().getUserId());
                        getView().loginSuccess();
                        // 设置别名
                        JPushHelper.getInstance().setAlias();
                    }else {
                        getView().loginFailure(loginResponseBaseResponse.getMsg());
                    }
                }, throwable -> {
                    getView().hideLoadingDialog();
                    getView().loginFailure(throwable.getLocalizedMessage());
                });
    }
}
